from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework_jwt.settings import api_settings
from rest_framework.generics import GenericAPIView


from .utils import OAuthQQ, logger
from .exceptions import QQAPIException
from .models import OauthQQUser
from .serializers import QQAuthUserSerializer
# Create your views here.


#  url(r'^qq/authorization/$', views.QQAuthURLView.as_view()),
class QQAuthURLView(APIView):
    """
    获取QQ登录的url
    """
    def get(self, request):
        """
        提供用于qq登录的url
        """
        # 获取next参数,前端设置的,决定回调时跳转的界面的地址
        # eg:http://www.meiduo.site:8080/oauth/qq/authorization/?next=fenghua.html
        # 会在跳转后的界面最后加上state=XXXX的跳转界面的网址
        # eg:http://www.meiduo.site:8080/oauth_callback.html?code=AE86607C39CC5A1178A6FECF615B79EF&state=fenghua.html
        next = request.query_params.get('next')
        # 创建oauth对象
        print('qq扫码后的回调地址是：', next)
        # 包含拼接url,获取access_token,openid
        oauth = OAuthQQ(state=next)
        # 获取ＱＱ扫码登录界面的网址
        login_url = oauth.get_qq_login_url()
        return Response({'login_url': login_url})


class QQAuthUserView(APIView):
    """
    QQ扫码登录的用户
    """
    def get(self, request):
        """
        获取qq登录的用户数据
        """
        code = request.query_params.get('code')
        if not code:
            return Response({'message': '缺少code'}, status=status.HTTP_400_BAD_REQUEST)
        # 包含拼接url,获取access_token,openid
        oauth = OAuthQQ()

        # 获取用户access_token和openid,面向封装,方法定义在utils
        try:
            access_token = oauth.get_access_token(code)
            openid = oauth.get_openid(access_token)
        except QQAPIException as e:
            logger.error(e)
            return Response({'message': 'QQ服务异常'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        # 判断用户是否存在
        try:
            qq_user = OauthQQUser.objects.get(openid=openid)
        except OauthQQUser.DoesNotExist:
            # 用户第一次使用QQ登录
            token_openid = oauth.generate_save_user_token(openid)  # 为了安全,使用its_dangrous传输openid,不使用明文
            return Response({'openid': token_openid})
        else:
            # 找到用户, 生成JWT_token
            user = qq_user.user
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            response = Response({
                'token': token,
                'user_id': user.id,
                'username': user.username
            })
            return response


class QQSockView(GenericAPIView):
    # 指定序列化器
    serializer_class = QQAuthUserSerializer

    def post(self, request):
        """
        绑定用户手机号和openid
        两种情况：
        １.手机号注册过－－－－>直接绑定
        2. 手机号没注册过－－－－>先保存用户再绑定
        :param request:
        :return:
        """
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        return Response({
            'token': user.token,
            'username': user.username,
            'user_id': user.id
        })